module.exports = {
  // 用户注册
  regUser: (req, res) => {
    const db = require('../db/index')
    // 加密密码的库
    const bcryptjs = require('bcryptjs')

    const userinfo = req.body
    // 判断账号和密码不能为空
    if (!userinfo.username || !userinfo.password) {
      return res.cc(1, '账号或密码不能为空!')
    }
    const sql = 'select * from ev_users where username=?'
    // 查询账号是否被占用
    db.query(sql, [userinfo.username], (err, result) => {
      if (err) {
        return res.cc(1, err)
      }
      if (result.length > 0) {
        return res.cc(1, '用户名被占用')
      }
      userinfo.password = bcryptjs.hashSync(userinfo.password, 10)
      const sql = 'insert into ev_users set ?'
      // 插入用户注册的信息
      db.query(sql, { username: userinfo.username, password: userinfo.password }, (err, result) => {
        if (err) {
          return res.cc(1, err)
        }
        if (result.affectedRows !== 1) {
          return res.cc(1, '注册失败')
        }
        // res.send({ status: 0, message: '注册成功' })
        res.cc(0, '注册成功')
      })
    })
  },
  // 登录
  login: (req, res) => {
    const db = require('../db/index')
    const bcryptjs = require('bcryptjs')

    const userinfo = req.body
    // 判断账号和密码不能为空
    if (!userinfo.username || !userinfo.password) {
      return res.cc(1, '用户名或密码不能为空')
    }
    const sql = 'select * from ev_users where username=?'
    // 查找用户名是否存在并且密码是否正确
    db.query(sql, [userinfo.username], (err, result) => {
      if (err) {
        return res.cc(1, err)
      }
      if (result.length !== 1) {
        return res.cc(1, '用户名不存在')
      }
      const compareResult = bcryptjs.compareSync(userinfo.password, result[0].password)
      if (!compareResult) {
        return res.cc(1, '密码错误')
      }
      const user = { ...result[0], user_pic: '' }
      const jwt = require('jsonwebtoken')
      const config = require('../config')
      const token = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
      res.send({
        status: 0,
        message: '登录成功',
        token: 'Bearer ' + token
      })
    })
  }
}